using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace minims_lib
{
	public class Transcoder
	{
		// public
		public string FileName;

		// private
		private Process encoderProc;

		private static FileInfo fbuffer = new FileInfo(@"transcodebuf.mpg");

		public int Start(FileInfo fi, string encoder)
		{
			// Check if file is available for read write
			if (fbuffer.Exists && fbuffer.IsReadOnly)
				return 0;

			encoderProc = new Process();

			encoderProc.StartInfo.FileName = encoder;
			encoderProc.StartInfo.WorkingDirectory = @"\";
			encoderProc.StartInfo.Arguments = ("\"" + fi.FullName + "\" -o \"" + fbuffer.FullName + "\" -of mpeg -mpegopts format=dvd -srate 48000 -af lavcresample=48000 -oac lavc -lavcopts acodec=ac3:abitrate=448 -vf pp=lb,harddup -ovc lavc -lavcopts vcodec=mpeg2video:vrc_buf_size=1835:vrc_maxrate=9000:vbitrate=4000:keyint=18:trell:mbd=2:ilme:ildct -ofps 24000/1001");
			encoderProc.StartInfo.UseShellExecute = false;
			encoderProc.StartInfo.RedirectStandardOutput = false;
			encoderProc.StartInfo.RedirectStandardError = false;
			encoderProc.StartInfo.CreateNoWindow = true;
			encoderProc.Start();
			FileName = fi.FullName;

			//Console.WriteLine(encoderProc.StandardOutput.);

			if (!encoderProc.Responding)
				return 1;
			else
				return 0;
		}

		public void Stop()
		{
			if (encoderProc.HasExited)
			{
				encoderProc.Dispose();
				encoderProc = null;
				return;
			}
			else if (encoderProc.Responding)
			{
				encoderProc.Kill();
				encoderProc.Dispose();
				encoderProc = null;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public bool Started
		{
			get
			{
				if (encoderProc != null)
				{
					if (encoderProc.HasExited)
						return false;

					return encoderProc.Responding;
				}

				return false;
			}
		}
	}
}
